package com.bothin.experiment4.controller;

import com.bothin.experiment4.model.Customer;
import com.bothin.experiment4.model.Product;
import com.bothin.experiment4.service.IProductService;
import com.bothin.experiment4.utils.KeyUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * Created by bothin
 * At 2019/12/17 9:19
 * Description:
 */
@Controller
@RequestMapping("/product")
@Secured("ROLE_USER_ADMIN")
public class ProductController {
    @Autowired
    private IProductService productService;

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "4") Integer size,
                             @RequestParam(value = "keyword", defaultValue = "") String keyword,
                             Map<String, Object> map){
        PageHelper.startPage(page,size);
        List<Product> products = null;
        if (!StringUtils.isEmpty(keyword)){
            products = productService.findByKeyword(keyword);
            map.put("key","&keyword="+keyword);
        }else {
            products = productService.findAll();
        }
        PageInfo<Product> pageInfo = new PageInfo<>(products);
        map.put("pageInfo", pageInfo);
        return new ModelAndView("product/list");
    }

    @GetMapping("/to/add")
    public ModelAndView toAdd(@RequestParam(value = "productId",required = false) String productId,
                              @RequestParam(value = "page",required = false) Integer page,
                              Map<String, Object> map){
        if (!StringUtils.isEmpty(productId)){
            Product product = productService.findById(productId);
            map.put("product", product);
            map.put("page", page);
        }
        return new ModelAndView("product/add",map);
    }

    @PostMapping("/add")
    @Transactional
    public ModelAndView add(Product product,@RequestParam(value = "page",required = false) Integer page){
        if (StringUtils.isEmpty(product.getProductId())){
            product.setProductId(KeyUtil.genUniqueKey());
            productService.insert(product);
        }else {
            productService.update(product);
        }
        return new ModelAndView("redirect:/product/list?page="+page);
    }
}
